package net.vinote.smart.platform.pool.thread;

import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ThreadPool {
	private static ThreadPool pool;
	private static final Object lock = new Object();
	private ExecutorService executor;
	private ScheduledExecutorService scheduleExe;

	private ThreadPool() {
	}

	public static ThreadPool getInstance() {
		if (pool == null) {
			synchronized (lock) {
				if (pool == null) {
					pool = new ThreadPool();
				}
			}
		}
		return pool;
	}

	/**
	 * 添加一线程任务
	 * 
	 * @param r
	 */
	public void addThread(Runnable r) {
		if (executor == null) {
			synchronized (this) {
				if (executor == null) {
					executor = Executors.newFixedThreadPool(Runtime
							.getRuntime().availableProcessors());
				}
			}
		}
		executor.execute(r);
	}

	/**
	 * 添加定时任务
	 * 
	 * @param task
	 * @param initialDelay
	 * @param delay
	 */
	public void addTimer(TimerTask task, long initialDelay, long period) {
		if (scheduleExe == null) {
			synchronized (this) {
				if (scheduleExe == null) {
					scheduleExe = Executors.newScheduledThreadPool(Runtime
							.getRuntime().availableProcessors());
				}
			}
		}
		scheduleExe.scheduleAtFixedRate(task, initialDelay, period,
				TimeUnit.MILLISECONDS);
	}
}
